package cn.netty.exemple2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

@ChannelHandler.Sharable
public class TimeServerHandler extends ChannelHandlerAdapter {

    private int counter;


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;

        System.out.println("The TimeServer receive order :"+body+"; the counter is :" + ++counter);


        String currentTime = "QUERY TIME ORDER"
                .equalsIgnoreCase(body) ?new Date(System.currentTimeMillis())
                .toString():"BAD ORDER";

        currentTime = currentTime + System.getProperty("line.separator");

        ByteBuf writ = Unpooled.copiedBuffer(currentTime.getBytes());

        ctx.writeAndFlush(writ);

    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server client to client");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("TimeServer error is close");
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
